<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Finance_Fenxiao_Index extends Stourweb_Controller
{
    public function before()
    {
        if(!St_Functions::is_normal_app_install('mobiledistribution'))
        {
            echo '未安装分销商应用';
            exit;
        }
        $moduels =  DB::select('id', 'modulename', 'pinyin','maintable','correct')
            ->from('model')
            ->where('is_orderable', '=', 1)
            ->execute()
            ->as_array();
        $this->assign('modules',$moduels);
        $this->assign('prefix_url','finance/admin/finance/fenxiao');
        parent::before();
    }

    public function action_commission()
    {
        $action = $this->params['action'];
        if (empty($action))  //显示分销接算,返佣明细.
        {

            $this->display('admin/finance/fenxiao/commission');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $startdate = Arr::get($_GET,'startdate');
            $enddate = Arr::get($_GET,'enddate');
            $typeid = $_GET['typeid'];
            $commission_status = $_GET['status'];
            $w = " where a.id >0 ";
            //结算状态
            if(!$commission_status)
            {
                $w.= " and b.status in(2,5)";
            }
            else
            {
                $w.= " and b.status = {$commission_status}";
            }
            //产品类型
            if(!empty($typeid))
            {
                $w.=" and b.typeid={$typeid} ";
            }
            //关键词
            if(!empty($keyword)){
                $w.="and b.ordersn='{$keyword}' ";
            }
            //时间
            if($startdate)
            {
                $w .=" and b.addtime >".strtotime($startdate);
            }
            if($enddate)
            {
                $w .=" and b.addtime <=".strtotime($enddate);
            }


            $sql = "select a.*,b.ordersn,b.status from  sline_fenxiao_data a left join sline_member_order b on a.order_id=b.id  $w order by b.addtime desc limit {$start},{$limit}";
            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from  sline_fenxiao_data a left join sline_member_order b on a.order_id=b.id $w")->execute()->as_array();
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $list = $this->format_result($list);
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
        else if ($action == 'save')   //保存字段
        {
        }
        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {
            $id=Arr::get($_POST,'id');
            $field=Arr::get($_POST,'field');
            $val=Arr::get($_POST,'val');
            $model=ORM::factory('fenxiao')->where('memberid','=',$id)->find();
            $curtime=time();
            if($model->id)
            {
                $model->$field=$val;
                if($field=='isfrozen')
                {
                    if($val==1)
                        $model->frozentime=$curtime;
                    else
                    {
                        $model->unfrozentime=$curtime;
                        $model->fxlogintime=$curtime;
                    }
                }
                $model->save();
                if($model->saved())
                    echo 'ok';
                else
                    echo 'no';
            }

        }

    }

    //分佣详情
    public function action_view()
    {
        $ordersn = Arr::get($_GET, 'ordersn');
        $sql = "select a.*,b.ordersn,b.status as order_status from  sline_fenxiao_data a left join sline_member_order b on (a.order_id=b.id) where b.ordersn='{$ordersn}'";
        $row = DB::query(Database::SELECT, $sql)->execute()->current();

        $order_info = Model_Member_Order::order_info($ordersn);
        $row['addtime'] = !empty($order_info['addtime']) ?date('Y-m-d H:i',$order_info['addtime']):'';
        $row['productname'] = $order_info['productname'];
        $row['total_payprice'] = $order_info['pay_price'];
        $row['productname'] = $order_info['productname'];
        $model = Model_Model::get_module_info($order_info['typeid']);
        $row['ordersn'] = $ordersn;
        $row['typename'] = $model['modulename'];

        //未结算状态,获取分销佣金
        if($row['order_status']!='5')
        {
            $row['total_commission'] = '0';
        }
        //已结算状态直接从结算记录里去获取.
        else
        {

            $row['member'] = $row['memberid'] ? Model_Member::get_member_info($row['memberid']) : array();
            $row['member1'] = $row['memberid1'] ? Model_Member::get_member_info($row['memberid1']) : array();
            $row['member2'] = $row['memberid2'] ? Model_Member::get_member_info($row['memberid2']) : array();
            $row['member3'] = $row['memberid3'] ? Model_Member::get_member_info($row['memberid3']) : array();
            $row['commission']  = !empty($row['memberid']) ? $this->getFxCommission($row,$row['memberid']) :0;
            $row['commission1']  =!empty($row['memberid1']) ? $this->getFxCommission($row,$row['memberid1']) :0;
            $row['commission2']  =!empty($row['memberid2']) ? $this->getFxCommission($row,$row['memberid2']) :0;
            $row['commission3']  =!empty($row['memberid3']) ? $this->getFxCommission($row,$row['memberid3']):0;
            $row['total_commission'] = $row['commission'] + $row['commission1'] + $row['commission2'] + $row['commission3'];

        }
        $this->assign('order_info',$row);

        $this->display('admin/finance/fenxiao/view');



    }


    /*
   * 生成excel页面
   * */
    public function action_excel()
    {
        $this->assign('params',$_GET);
        $this->display('admin/finance/fenxiao/excel');
    }

    public function action_genexcel()
    {
        $timetype = $this->params['timetype'];
        $starttime = empty($_GET['starttime'])? null:strtotime($_GET['starttime'].' 00:00:00');
        $endtime =empty($_GET['endtime'])?null: strtotime($_GET['endtime'].' 23:59:59');

        $time_arr = array();

        switch ($timetype)
        {
            case 1:
                $time_arr = St_Functions::back_get_time_range(1);
                break;
            case 2:
                $time_arr = St_Functions::back_get_time_range(2);
                break;
            case 3:
                $time_arr = St_Functions::back_get_time_range(3);
                break;
            case 5:
                $time_arr = St_Functions::back_get_time_range(5);
                break;
            case 6:
                $time_arr = array($starttime, $endtime);
                break;
        }

        $w = " where a.id >0 ";
        //开始结束时间
        $w  .= " and a.addtime > $time_arr[0] and  a.addtime < $time_arr[1] " ;
        $sql = "select a.*,b.ordersn,b.status,b.typeid from  sline_fenxiao_data a left join sline_member_order b on a.order_id=b.id  $w ";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
         $this->gene_excel($list);

    }
    protected function gene_excel($order_list)
    {

        $titles = array('下单时间','订单号','产品类型','产品名称','结算状态','营业收入','分销佣金总额');
        $rows = array();
        foreach ($order_list as $row)
        {
            $settle_status = $row['status'] == 5 ? '已结算' : '未结算';
            //产品类型
            $order_info = Model_Member_Order::order_info($row['ordersn']);
            $row['productname'] = $order_info['productname'];
            $row['total_payprice'] = $order_info['pay_price'];
            $row['productname'] = $order_info['productname'];
            $model = Model_Model::get_module_info($order_info['typeid']);
            $row['typename'] = $model['modulename'];
            //未结算状态,获取分销佣金
            if($row['status']!='5')
            {
                $row['total_commission'] = '--';
            }
            //已结算状态直接从结算记录里去获取.
            else
            {
                $row['commission']  = !empty($row['memberid']) ? $this->getFxCommission($row,$row['memberid']) :0;
                $row['commission1']  =!empty($row['memberid1']) ? $this->getFxCommission($row,$row['memberid1']) :0;
                $row['commission2']  =!empty($row['memberid2']) ? $this->getFxCommission($row,$row['memberid2']) :0;
                $row['commission3']  =!empty($row['memberid3']) ? $this->getFxCommission($row,$row['memberid3']):0;
                $row['total_commission'] = $row['commission'] + $row['commission1'] + $row['commission2'] + $row['commission3'];

            }
            $rows[] = array(
                date('Y-m-d H:i:s',$row['addtime']),
                $row['ordersn'],
                $row['typename'],
                $row['productname'],
                $settle_status,
                $row['total_payprice'],
                $row['total_commission']
            );
        }
        $td_width = array(25,25,10,50,10,15,15);
        $col_style = array('string','string','string','string','string','string');
        St_File::export_excel($rows, $titles, $td_width, $col_style);

    }
    protected function format_result($list)
    {
        foreach($list as &$row)
        {
            $order = DB::select('productname','id')->from('member_order')
                ->where('ordersn','=',$row['ordersn'])
                ->execute()
                ->current();
            $price = Model_Member_Order_Compute::get_order_price($order['id']);

            $row['addtime'] = !empty($row['addtime'])?date('Y-m-d H:i',$row['addtime']):'';
            $order_info = Model_Member_Order::order_info($row['ordersn']);
            $row['productname'] = $order['productname'];
            $row['total_payprice'] = $price['pay_price'];

            $model = Model_Model::get_module_info($order_info['typeid']);
            $row['typename'] = $model['modulename'];

            //未结算状态,获取分销佣金
            if($row['status']!='5')
            {
                $row['total_commission'] = '--';
            }
            //已结算状态直接从结算记录里去获取.
            else
            {
                $row['commission']  = !empty($row['memberid']) ? $this->getFxCommission($row,$row['memberid']) :0;
                $row['commission1']  =!empty($row['memberid1']) ? $this->getFxCommission($row,$row['memberid1']) :0;
                $row['commission2']  =!empty($row['memberid2']) ? $this->getFxCommission($row,$row['memberid2']) :0;
                $row['commission3']  =!empty($row['memberid3']) ? $this->getFxCommission($row,$row['memberid3']):0;
                $row['total_commission'] = $row['commission'] + $row['commission1'] + $row['commission2'] + $row['commission3'];

            }
        }
        return $list;
    }






    /**
     * 获取分销佣金
     * @param $order
     * @param $fx_member_id
     * @return mixed
     */
    private function getFxCommission($order,$fx_member_id)
    {
        $amount = DB::select()->from('fenxiao_record')
            ->where('memberid','=',$fx_member_id)
            ->and_where('fxmemberid','=',$order['memberid'])
            ->and_where('orderid','=',$order['order_id'])
            ->and_where('type','=',0)
            ->execute()
            ->get('amount');
        return $amount ? $amount : 0;

    }


}